package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    public Server(){
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            threadPool = Executors.newFixedThreadPool(30);
            System.out.println("服务端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while(true) {
                System.out.println("等待客户端链接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端链接了！");

                ClientHandler handler = new ClientHandler(socket);
//                Thread t = new Thread(handler);
//                t.start();
                threadPool.execute(handler);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }
        public void run(){
            try {
                InputStream in = socket.getInputStream();
                // 使用InputStreamReader包装输入流，指定字符集为UTF-8，以正确读取字符
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                // 使用BufferedReader进一步包装，以便按行读取数据
                BufferedReader br = new BufferedReader(isr);
                String message;
                // 循环读取客户端发送的消息，直到连接关闭
                while ((message = br.readLine()) != null) {
                    // 打印读取到的客户端消息
                    System.out.println("客户端说:" + message);
                }
            } catch (IOException e) {
                // 打印异常信息，以便调试和日志记录
                e.printStackTrace();
            }
        }
    }

}







